<?php

$r = FALSE;
if(!empty($_POST['f']))
{  
   if(!empty($_POST['f']['name']) && !empty($_POST['f']['email']) && $FILTER->isValidEmail($_POST['f']['email']))
   {
      $userData = array();
      $userData['login']  = $_POST['f']['email'];
      $userData['email']  = $_POST['f']['email'];
      $userData['name']   = $_POST['f']['name'];
      $userData['vdate']  = time() + 5*24*60*60;
      $userData['key']    = config::read('salt', 'file') . $userData['email'] . time();
      $userData['active'] = 0;

      $_U = new user();
      
      if($_U->loadByEmail($userData['email']))
      {
         # Update exists User - adding to the subscribers group
         
         $_U_groups = $_U->getGroups();
         $_U_groups = empty($_U_groups) ? array() : array_keys($_U_groups);
         if(!in_array(4, $_U_groups))
         {
            $_U_groups[] = 4;
            $_U->setGroups($_U_groups);
            $r = 'subscribed';
         }
      } elseif($_U->save($userData))
      {
         # Create a new User with subscriber group
         
         $_U->setGroups(array(4));
         $_U->changePassword(TRUE, config::read('salt', 'file') . time());

         $message = email::getMessageFromTemplate(
            array(
               'username' => $_U->name,
               'key'      => $_U->key
            ), 
            'email/subscribe.html');
         
         $r = email::queue(
            $_U->email, 
            gettext::translate('subscribe', 'confirm_subject'), 
            $message, 
            array(
               'recipient_name' => $_U->name
            ));
         if($r) $r = 'registered';
      }
   }
   
   if($r)
   { 
      $ErrorHandler->setSuccess(array(
         'code' => $r
      ));
   } else
   {
      $ErrorHandler->setError();
   }
} elseif(request::getRequest('last') == 'confirm')
{
   $key = request::getRequest('path', request::getRequest('length') - 1);
   $_U  = new user();
   $_U->loadByKey($key);

   if($_U->login != "")
   {
      $userData = array();
      $userData['key']    = '';
      $userData['active'] = 1;
      if($_U->save($userData))
      {
         $r = TRUE;
      }
   }
   
   if($r)
   { 
      $ErrorHandler->setSuccess(array(
         'code' => 'confirmed'
      ));
   } else
   {
      $ErrorHandler->setError();
   }
} elseif(request::getRequest('last') == 'unsubscribe')
{
   $key = request::getRequest('path', request::getRequest('length') - 1);
   $uid = request::getRequest('path', request::getRequest('length') - 2);
   $_U = new user($uid);

   if($_U->login != "" && $key == dispatch::getUserHash($_U))
   {
      $_U_groups = $_U->getGroups();
      if(is_array($_U_groups) && isset($_U_groups[4]))
      {
         unset($_U_groups[4]);
         $_U_groups = array_keys($_U_groups);
         $_U->setGroups($_U_groups);
         
         $ErrorHandler->setSuccess(array(
            'code' => 'unsubscribed'
         ));
      }
   }
}